package 链表与双指针.m03.d21.t03;

import 链表与双指针.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    private ListNode reverse(ListNode head) {
        ListNode cur = head, pre = null;
        while(cur != null)  {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
    public boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null) {
            return true;
        }
        ListNode slow = head, fast = head.next;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        if(fast != null && fast.next == null) {
            ListNode tmp = slow;
            slow = slow.next;
            tmp.next = null;
        }
        ListNode start = reverse(slow);
        while(start != null && head != null && start.val == head.val) {
            start = start.next;
            head = head.next;
        }
        if(start == null && head == null) {
            return true;
        }
        if(start == null || head == null) {
            return false;
        }
        if(start.val != head.val) {
            return false;
        }
        return true;
    }
}